package com.admin.common.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.admin.common.constant.SystemConstants;
import com.admin.common.enums.GenderEnum;
import com.admin.common.enums.IBaseEnum;
import com.admin.common.enums.StatusEnum;
import com.admin.common.util.SpringContextUtil;
import com.admin.module.system.entity.SysRole;
import com.admin.module.system.entity.SysUser;
import com.admin.module.system.entity.SysUserRole;
import com.admin.module.system.service.SysRoleService;
import com.admin.module.system.service.SysUserRoleService;
import com.admin.module.system.service.SysUserService;
import com.admin.module.system.vo.UserImportVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户导入监听器
 * @Author: suYan
 * @Date: 2024-01-22
 */
@Slf4j
public class UserImportListener extends MyAnalysisEventListener<UserImportVO> {

    // 有效条数
    private int validCount;

    // 无效条数
    private int invalidCount;


    // 导入返回信息
    StringBuilder msg = new StringBuilder();


    private final PasswordEncoder passwordEncoder ;

    private final SysUserService sysUserService;

    private final SysUserRoleService userRoleService;

    private final SysRoleService roleService;



    public UserImportListener() {
        this.passwordEncoder = SpringContextUtil.getBean(PasswordEncoder.class);
        this.sysUserService = SpringContextUtil.getBean(SysUserService.class);
        this.userRoleService = SpringContextUtil.getBean(SysUserRoleService.class);
        this.roleService = SpringContextUtil.getBean(SysRoleService.class);
    }



    /**
     * 每一条数据解析都会来调用
     *
     * 1. 数据校验，全字段校验
     * 2. 数据持久化
     * @param userImportVO easyExcel 每一行数据，是一个对象实例
     * @param analysisContext
     */
    @Override
    public void invoke(UserImportVO userImportVO, AnalysisContext analysisContext) {
        log.info("解析到一条用户数据：{}", userImportVO);
        // 校验数据
        StringBuilder validationMsg = new StringBuilder();
        String userName = userImportVO.getUsername();

        // 校验用户名
        if (StringUtils.isBlank(userName)) {
            validationMsg.append("用户名为空: ");
        } else {
            long count = sysUserService.count(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, userName));
            if (count > 0) {
                validationMsg.append("用户名已存在");
            }
        }

        // 校验手机号
//        String phone = userImportVO.getMobile();
//        if (StringUtils.isBlank(phone)) {
//            validationMsg.append("手机号为空：");
//        }

        if (validationMsg.length() == 0) {
            // 校验通过，持久化到数据库
            SysUser user = this.convertToUser(userImportVO);
            user.setPassword(passwordEncoder.encode(SystemConstants.DEFAULT_PASSWORD));
            // 性别翻译
            String genderLabel = userImportVO.getGender();
            if (StringUtils.isNotEmpty(genderLabel)) {
                Integer genderValue = (Integer) IBaseEnum.getValueByLabel(genderLabel, GenderEnum.class);
                user.setGender(genderValue);
            }


            boolean result = sysUserService.save(user);

            if (result) {
                validCount++;
                if (StringUtils.isNotEmpty(userImportVO.getRoleNames())) {
                    // 根据 roleCode 找出角色表中的 roleIds
                    LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
                    wrapper.in(SysRole::getRoleName, userImportVO.getRoleNames());
                    wrapper.eq(SysRole::getStatus, StatusEnum.ENABLE.getValue());
                    List<SysRole> roleList = roleService.list(wrapper);
                    List<Long> roleIds = roleList.stream()
                            .map(SysRole::getRoleId)
                            .collect(Collectors.toList());

                    // 保存用户角色表关联
                    List<SysUserRole> userRoleList = roleIds.stream()
                            .map(roleId -> new SysUserRole(user.getUserId(), roleId))
                            .collect(Collectors.toList());
                    userRoleService.saveBatch(userRoleList);


                }
            } else {
                invalidCount++;
                msg.append("第").append(validCount + invalidCount).append("行数据保存失败; <br/>");
            }

        } else {
            invalidCount++;
            msg.append("第").append(validCount + invalidCount + "行数据校验失败: ").append(validationMsg + "<br/>");
        }




    }


    private SysUser convertToUser(UserImportVO userImportVO) {
        SysUser user = new SysUser();
        user.setUsername(userImportVO.getUsername());
        user.setRealName(userImportVO.getRealName());
        user.setMobile(userImportVO.getMobile());
        user.setEmail(userImportVO.getEmail());
        user.setCreateTime(userImportVO.getCreateTime());
        user.setStatus(StatusEnum.ENABLE.getValue());
        return user;
    }


    /**
     * 所有数据解析完成会来调用
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    @Override
    public String getMsg() {
        return "导入用户结束：成功" + validCount + "条，失败" + invalidCount + "条 "+  msg;
    }




}
